package com.example.mptnet;

import static android.app.job.JobInfo.PRIORITY_DEFAULT;
import static android.content.Context.MODE_PRIVATE;

import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Build;
import android.util.Log;

import androidx.annotation.RequiresApi;
import androidx.core.app.NotificationCompat;

import com.example.mptnet.Interfaces.API;
import com.example.mptnet.Models.RP;
import com.example.mptnet.Models.User;

import java.time.DayOfWeek;
import java.time.LocalDate;
import java.time.format.TextStyle;
import java.util.ArrayList;
import java.util.Locale;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;

public class Receiver extends BroadcastReceiver {
    String text = "";
    SharedPreferences settings;
    ArrayList<RP> rp = new ArrayList<RP>();
    String UID = "";
    User user = new User();
    API api;
    Retrofit retrofit;
    private static final String flag = "123";
    final int id = 123;
    NotificationManager manager;
    @Override
    public void onReceive(Context context, Intent intent) {
        retrofit = Builder.request();
        settings = context.getSharedPreferences("SETTINGS",MODE_PRIVATE);
        api = retrofit.create(API.class);
        UID = settings.getString("UID", "");
        Call<User> calluser = api.GetUser(UID);
        manager = (NotificationManager)context.getSystemService(Context.NOTIFICATION_SERVICE);
        calluser.enqueue(new Callback<User>() {
            @RequiresApi(api = Build.VERSION_CODES.O)
            @Override
            public void onResponse(Call<User> call, Response<User> response) {
                if (response.isSuccessful()) {
                    user = response.body();
                    if (!user.getUsers_group().equals("default")) {
                        DayOfWeek day = LocalDate.now().getDayOfWeek();
                        Call<ArrayList<RP>> callRP = api.GetRP(user.getUsers_group());
                        callRP.enqueue(new Callback<ArrayList<RP>>() {
                            @Override
                            public void onResponse(Call<ArrayList<RP>> call, Response<ArrayList<RP>> response) {
                                if (response.isSuccessful()) {
                                    rp = response.body();
                                    for (RP item : rp)
                                        if (item.weekday.equals(day.getDisplayName(TextStyle.FULL, new Locale("ru")).toUpperCase(Locale.ROOT)))
                                            text = item.get_rp();
                                    if (text.equals(""))
                                        text = "Седня выходной";
                                    text = text.replaceAll("\n\n+", "\n");
                                    sendNotification(text, context);
                                }
                            }

                            @Override
                            public void onFailure(Call<ArrayList<RP>> call, Throwable t) {
                                Log.e("Ошибка", t.getMessage());
                            }
                        });
                    }
                }

            }
            @Override
            public void onFailure(Call<User> call, Throwable t) {
                Log.e("Ошибка", t.getMessage());

            }
        });
    }
    private void onNotificationClicked(){

    }
    private void sendNotification(String text, Context context) {

        Intent intent = new Intent(context, UserWindow.class);
        intent.addFlags(intent.FLAG_ACTIVITY_CLEAR_TASK | intent.FLAG_ACTIVITY_NEW_TASK);
        NotificationCompat.Builder builder =
                new NotificationCompat.Builder(context,"channel_id")
                        .setAutoCancel(true)
                        .setWhen(System.currentTimeMillis())
                        .setContentText(text)
                        .setContentTitle("Расписание на сегодня")
                        .setPriority(PRIORITY_DEFAULT)
                        .setDefaults(Notification.DEFAULT_ALL)
                        .setSmallIcon(R.mipmap.bg_loading_round)
                        .setStyle(new NotificationCompat.BigTextStyle().bigText(text));
        createNotificationChannel(manager);
        manager.notify(123,builder.build());
    }
    public static void createNotificationChannel(NotificationManager manager){
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            NotificationChannel notificationChannel = new NotificationChannel(flag,flag, NotificationManager.IMPORTANCE_DEFAULT);
            manager.createNotificationChannel(notificationChannel);
        }
    }
}
